/**
 * 开放 Promise的 resolve与reject接口
 */
export default class PromiseReveal<T = any> {

    private main_pms: Promise<T>;
    private pms: Promise<T>;
    private res: Function;
    private rej: Function;

    private cache: Promise<T>;

    static create() {
        return new PromiseReveal()
    }

    constructor(executor?: (resolve: (value: T | PromiseLike<T>) => void, reject: (reason?: any) => void) => void) {
        this.pms = new Promise<T>((resolve, reject) => {
            this.res = resolve;
            this.rej = reject;
        })
        if (executor != null) {
            this.main_pms = new Promise(executor);
        }
    }

    then<TResult1 = T, TResult2 = never>(onfulfilled?: ((value: T) => TResult1 | PromiseLike<TResult1>) | undefined | null, onrejected?: ((reason: any) => TResult2 | PromiseLike<TResult2>) | undefined | null) {
        return this.result().then(onfulfilled, onrejected);
    }


    resolve(v?: T) {
        this.res(v);
    }

    reject(reason?: any) {
        this.rej(reason);
    }

    private result() {
        if (!this.main_pms) {
            return this.pms;
        }
        return this.cache || (this.cache = Promise.race([this.main_pms, this.pms]));
    }

}




